﻿using Org.BouncyCastle.Utilities.Encoders;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Jim.Core;

public static class CyptoExtension
{
    /// <summary>
    /// Url 加密
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string UrlEncode(this string str) => HttpUtility.UrlEncode(str, Encoding.UTF8);
    /// <summary>
    /// Url 解密
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string UrlDecode(this string str)  => HttpUtility.UrlDecode(str, Encoding.UTF8); 

    /// <summary>
    /// SHA256加密
    /// </summary>
    /// <param name="array">文本数组</param>
    /// <param name="withSort">是否需要排序</param>
    /// <returns></returns>
    public static string SHA256(this string[] array,bool withSort=false)
    {
        if (withSort) Array.Sort<string>(array, StringComparer.Ordinal);
        string signStr = string.Join("", array);
        byte[] signBytes = Encoding.UTF8.GetBytes(signStr);
        SHA256 shA256 = System.Security.Cryptography.SHA256.Create();
        string sign = Hex.ToHexString(shA256.ComputeHash(signBytes));
        return sign;
    }
}